package com.test.textGame.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.textGame.algorithm.TopK;
import com.test.textGame.dao.Top10Dao;
import com.test.textGame.domain.Player;
import com.test.textGame.domain.Top10;
import com.test.textGame.dto.Score;
import com.test.textGame.enums.MqLogTypeEnum;
import com.test.textGame.exception.GameErrorCode;
import com.test.textGame.exception.GameRuntimeException;
import com.test.textGame.mq.RabbitMqRedisProducer;
import com.test.textGame.service.MqFailLogService;
import com.test.textGame.service.Top10Service;
import com.test.textGame.transaction.TransactionProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Auto created by codeAppend plugin
 */
@Slf4j
@Service
public class Top10ServiceImpl extends ServiceImpl<Top10Dao, Top10> implements Top10Service {

    @Autowired
    private RabbitMqRedisProducer rabbitMqRedisProducer;
    @Autowired
    private MqFailLogService mqFailLogService;
//    @Autowired
//    private RabbitMqMysqlProducer rabbitMqMysqlProducer;
    @Value("${rocketmq.mysql.consumer.topics}")
    private String topics;
    @Autowired
    private TransactionProducer transactionProducer;

    private static final TopK topK = new TopK(10);

    @Override
    public void consumeSlaverMsg(Player player, Integer gameScore) throws MQClientException {
        //比较分数大小并更新排行榜
        TopK.Node node = topK.add(player, gameScore);

        if (node != null) {
            //事务消息
            List<Score> scores = topK.topK();
            String msg = JSONObject.toJSONString(scores);
            try {
                TransactionSendResult result = transactionProducer.send(msg, topics);
                //发送半消息失败
                if (null == result || !SendStatus.SEND_OK.equals(result.getSendStatus())) {
                    throw new GameRuntimeException(GameErrorCode.HALF_MSG_FAIL);
                }
            } catch (Exception e) {
                log.error("发送半消息失败", e);
                mqFailLogService.saveLog(MqLogTypeEnum.HALF_MSG_FAIL, msg);
            }



            //可能发生缓存一致性问题，改用事务消息
//            //消息发送给redis
//            List<Score> scores = topK.topK();
//            String msg = JSONObject.toJSONString(scores);
//            try {
//                rabbitMqRedisProducer.sendScoreList(msg);
//            } catch (Exception e) {
//                System.out.println("给redis发消息失败e:"+e);
//                mqFailLogService.saveLog(MqLogTypeEnum.SEND_REDIS_FAIL, msg);
//            }
//
//            //持久化到mysql
//            Top10 entity = new Top10();
//            entity.setUserId(node.player.getUserId());
//            entity.setUserName(node.player.getUserName());
//            entity.setGameScore(node.score);
//            String msg2 = JSONObject.toJSONString(entity);
//            rabbitMqMysqlProducer.saveMysql(msg2);
        }
    }

}